<?php
namespace Managers;
use Engine\Functions as FUNCTS;
use Engine\Auth;

class Message extends \Lib\Model\DoctrineManager{

    
    public function getAllMessages($allMessages = false) {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('a')
                ->from('Entities\Message', 'a');
                
				
		$qb->andWhere('a.display != 6');
		$qb->orderBy('a.createdAt', 'DESC');
		 
		 
        $result = $qb->getQuery()->getResult();
        return $result;
        
    }
	
	public function getAttachedMessages() {

        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('a')
                ->from('Entities\Message', 'a')
				->where('a.display = 2');		
         
        $result = $qb->getQuery()->getResult();
        return $result;
        
    }
    
    public function getParamsToAllMessages() {
        
        
        $alias = "a";
        
        $allArguments = func_get_args();
        $queryParameters = array();
        foreach ($allArguments as $fieldInDataBase){
            $queryParameters[]=$alias.'.'.$fieldInDataBase;
        }
        
        $queryParameters = \implode(", ", $queryParameters);
        
        
        if (!count($queryParameters)){
            $queryParameters = '';
        }else{
            $alias = "";
        }
        
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select($alias.$queryParameters)
                ->from('Entities\Message', 'a');

        $result = $qb->getQuery()->getResult();
        return $result;
    }
    
    public function getLastParents($withHidden = false, $type=null, $maxResults=1000) {
        
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('m')
                ->from('Entities\Message', 'm')
                ->where('m.messageId = m.parentId');
                
        
        
        if ($type){
               $qb->andWhere('m.Type = :myType');
               $qb->setParameters(array('myType'=>$type));
        }
        
        if (!$withHidden){
               $qb->andWhere('m.display > 0');
                  
        }
        
        
        $qb->orderBy('m.createdAt', 'DESC');
        $qb->setMaxResults($maxResults);
        
        $result = $qb->getQuery()->getResult();
        
        return $result;
        
    }
    
    public function getMessageChilds($parentId=0, $withParent=true) {
        
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('m')
                ->from('Entities\Message', 'm');
        
        if($parentId !== 0){
            $qb->where('m.parentId = :parentId')
               ->setParameter('parentId', $parentId);
        }
        if(!$withParent){
            $qb->andWhere('m.messageId != :parentId')
               ->setParameter('parentId', $parentId);
        }
        $result = $qb->getQuery()->getResult();
        
        return $result;

        
    }
    
    public function getMessage($messageId){
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('m')
                ->from('Entities\Message', 'm')
                ->where('m.messageId = :messageId')
                ->setParameter('messageId', $messageId);
        $result = $qb->getQuery()->getSingleResult();
        return $result;
    }
	
    public function getHistory($limit = false){
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                 ->select('l')
                 ->from('Entities\AutoLog', 'l')
				 ->orderBy('l.createdAt', 'DESC')
				 ->setMaxResults($limit?$limit:1000);
        
		$result = $qb->getQuery()->getResult();

        return $result;
    }
    
    public function getAllMessagesChildsCounts() {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('count(m)')
                ->from('Entities\Message', 'm')
                ->groupBy('m.parentId');
        $result = $qb->getQuery()->getResult();
        return $result;

    }
    
    public function getAllMessageTypes() {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('m')
                ->from('Entities\Messagetype', 'm');
                
        $result = $qb->getQuery()->getResult(); 
        return $result;
    }
    
    public function addMessage($parameters) {
		
        $userId = Auth\CurrentUser::getId();
        $em = $this->getEntityManager();
        
        $em->getConnection()->beginTransaction();
        
        try {
            
            if ($parameters['messageIdFromGet'] != "-1"){
				$newMessage = $em->getReference('Entities\Message', $parameters['messageIdFromGet']);
                $newMessage->setUdpatedAt(new \DateTime());
            }else{
                $newMessage = new \Entities\Message();
                $newMessage->setCreatedAt(new \DateTime());	
                $newMessage->setUdpatedAt(new \DateTime());
            }

			$newMessage->setTitle($parameters['inputTitle']);
            $newMessage->setText($parameters['inputText']);
            $newMessage->setKeywords($parameters['keywords']);
            $newMessage->setSeoOptions($parameters['seoOptions']);
			
            $newMessage->setUser($em->getReference('\Entities\Profile', $parameters['userId']));
            $newMessage->setType($em->getReference('\Entities\MessageType', $parameters['publicationTypeId']));
            
            $newMessage->setDeletedAt(null);
            $newMessage->setMessageRank(1);
            

            if ($parameters['submitPublicate']) {
                $newMessage->setDisplay(1);
            } else {
                $newMessage->setDisplay(0);
            }

            $em->persist($newMessage);
            $em->flush();
            
			
            if (isset($parameters['parentId']) && $parameters['parentId'] == 'new'){
                $newMessage->setParentId($newMessage->getMessageId());
                
            }else{
                
                if ($newMessage->getParentId() == $newMessage->getMessageId()){
                    
                    $newMessage->setParentId($newMessage->getMessageId());
                }else{
                    $newMessage->setParentId($newMessage->getParentId());
                }
            }
            $em->flush();

            
            $em->getConnection()->commit();
        } catch (Exception $exc) {
            $em->getConnection()->rollback();
        }
        
        return $newMessage;
    }
    
    public function addComment($user, $parameters) {
        
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder();
        
        $comment = new \Entities\Comment();
        $log = new \Entities\AutoLog();
        $em->getConnection()->beginTransaction();
        
        try {
            $comment->setParentId($parameters['parentId']);
            $comment->setCreatedAt(new \DateTime());
            $comment->setText($parameters['commentText']);
            $comment->setUser($user);
            $comment->setCommentRank(1);
            
            
            
            
            $em->persist($comment);
            $em->flush();

            $log->setCreatedAt(new \DateTime());
            $log->setUser($user);
            $log->setObjectId($parameters['parentId']);
            $log->setTypeLog("13");
            
            $em->persist($log);
            $em->flush();
            
            $em->commit();
        } catch (Exception $exc) {
            $em->getConnection()->rollBack();
        }
    }
    
    public function getAllQuickNews() {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                 ->select('q')   
                 ->from('Entities\QuickNews', 'q')
                 ->orderBy('q.createdAt', 'DESC')
                  ->setMaxResults(5);
        
        $result = $qb->getQuery()->getResult();
        
        return $result;
        
    }
    
    public function getAllComments($messageId){
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('c')
                ->from('Entities\Comment', 'c')
                ->where('c.parentId = :messageId')
                ->setParameter('messageId', $messageId)
                ->orderBy('c.createdAt', 'DESC');
        
        $result = $qb->getQuery()->getResult();
        return $result;
    }
    
    public function getAllCommentsByUser($userId){
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('c')
                ->from('Entities\Comment', 'c')
                ->where('c.User = :userId')
                ->setParameter('userId', $em->getReference('Entities\Profile', $userId))
                ->orderBy('c.createdAt', 'DESC');
        
        $result = $qb->getQuery()->getResult();
        return $result;
    }
    
    public function addResponceAjax($commentId, $userId){
        
    }
    
    public function getRandomAphorism($count = 3) {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('a, RAND() rand')
                ->orderBy('rand')
                ->from('Entities\Aphorism', 'a')
                ->setMaxResults($count);
        
        
        
        
        $result = $qb->getQuery()->getResult();
        $result = FUNCTS\ParseAndConvert::compressToList($result, '0');
        
        return $result;

    }
    
    public function getLastParentsByUser($userId) {
        
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('m')
                ->from('Entities\Message', 'm')
                ->where('m.User = :userId')
                ->andWhere('m.messageId = m.parentId')
                ->setParameter('userId', $em->getReference('Entities\Profile', $userId))
                ->orderBy('m.createdAt', 'DESC');
        $result = $qb->getQuery()->getResult();
        return $result;
        
    }
    
    public function getAllVideosCount() {
       $em = $this->getEntityManager();
       
       $qb = $em->createQueryBuilder()
                ->select('count(m)')
                ->from('Entities\Message', 'm')
                ->where('m.Type = :type')
                ->setParameter('type', 6);
        
        $result = $qb->getQuery()->getSingleScalarResult();
        
        return $result;
    }
    
    public function getMessagelikeText($text) {
        $words=preg_match_all("/[А-Яа-я\wрстуфхцчшщьыъэю’\']+/", $text, $match);
        $match=$match[0];
        
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('m')
                ->from('Entities\Message', 'm')
                ->where("m.text > ''");
                foreach($match as $key=>$like){
                    $like = '%'.$like.'%';
                    $qb->andWhere("m.text like :text$key");
                    $qb->setParameter("text$key", $like);
                }
   $result = $qb->getQuery()->getResult();
//    $result = $qb->getQuery()->getSQL();
//        
//        print "<pre>";
//        print_r($result);
//        print "</pre>";
//        die("++");
        return $result;
        
        
    }

    public function getAphoLikeText($text) {
        $words=preg_match_all("/[А-Яа-я\wрстуфхцчшщьыъэю’\']+/", $text, $match);
        
        $words=mb_ereg("/[А-Яа-я\wрстуфхцчшщьыъэю’\']+/", $text, $match);
        
        if(isset($match[0])) $match=$match[0];
        
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder()
                ->select('m')
                ->from('Entities\Aphorism', 'm')
                ->where("m.text > ''");
        
                foreach($match as $key=>$like){
//                    print "-".$like."-";
                    $qb->andWhere("m.text like :text$key OR m.theme like :texttheme$key");
                    
                    $qb->setParameter('text'.$key, "%$like%");
                    $qb->setParameter('texttheme'.$key, "%$like%");
//                    $qb->setParameters(array("text" => "%".$like,"%", "texttheme"=>"%".$like."%"));
                }
        $qb->setMaxResults(300);
        $result = $qb->getQuery()->getResult();  
        
        return isset($result)?$result:false;
    }
	
	
}